/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package light;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.swing.JOptionPane;
import javax.swing.JTextField;
import javax.swing.table.TableModel;

import net.Client;
import util.AppFeatures;
import util.Employee;
import util.Institution;
import handler.CallHandler;

public class LightApp extends javax.swing.JApplet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	private AppFeatures service = null;

	Client client = null;
	static CallHandler callHandler = new CallHandler();

	private final static int DEFAULT_PORT_NUMBER = 1099;
	private static int port = DEFAULT_PORT_NUMBER;

	private static String serverLocation = "localhost";

	public LightApp() {
		try {
			this.client = new Client(serverLocation, port, callHandler);
			this.service = (AppFeatures) client.getGlobal(AppFeatures.class);
		} catch (IOException ex) {
			Logger.getLogger(LightApp.class.getName()).log(Level.SEVERE, null,
					ex);
		}
	}

	/**
	 * Initializes the applet LightApp
	 */
	@Override
	public void init() {
		/* Set the Nimbus look and feel */
		// <editor-fold defaultstate="collapsed"
		// desc=" Look and feel setting code (optional) ">
		/*
		 * If Nimbus (introduced in Java SE 6) is not available, stay with the
		 * default look and feel. For details see
		 * http://download.oracle.com/javase
		 * /tutorial/uiswing/lookandfeel/plaf.html
		 */
		try {
			for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager
					.getInstalledLookAndFeels()) {
				if ("Nimbus".equals(info.getName())) {
					javax.swing.UIManager.setLookAndFeel(info.getClassName());
					break;
				}
			}
		} catch (ClassNotFoundException | InstantiationException
				| IllegalAccessException
				| javax.swing.UnsupportedLookAndFeelException ex) {
			java.util.logging.Logger.getLogger(LightApp.class.getName()).log(
					java.util.logging.Level.SEVERE, null, ex);
		}
		// </editor-fold>

		/* Create and display the applet */
		try {
			java.awt.EventQueue.invokeAndWait(new Runnable() {
				@Override
				public void run() {
					initComponents();
				}
			});
		} catch (InterruptedException | InvocationTargetException ex) {
		}
	}

	/**
	 * This method is called from within the init() method to initialize the
	 * form. WARNING: Do NOT modify this code. The content of this method is
	 * always regenerated by the Form Editor.
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	// <editor-fold defaultstate="collapsed"
	// desc="Generated Code">//GEN-BEGIN:initComponents
	private void initComponents() {

		jToolBar1 = new javax.swing.JToolBar();
		institutionsComboBox = new javax.swing.JComboBox();
		jSeparator1 = new javax.swing.JToolBar.Separator();
		addButton = new javax.swing.JButton();
		updateButton = new javax.swing.JButton();
		deleteButton = new javax.swing.JButton();
		searchButton = new javax.swing.JButton();
		jToolBar2 = new javax.swing.JToolBar();
		serverpropertiesButton = new javax.swing.JButton();
		refreshButton = new javax.swing.JButton();
		jScrollPane1 = new javax.swing.JScrollPane();
		table = new javax.swing.JTable();

		jToolBar1.setRollover(true);

		institutionsComboBox
				.setModel(new javax.swing.DefaultComboBoxModel(new String[] {
						"FST", "ENIT", "ISI", "INSAT", "ENSIT", "ENSI" }));
		institutionsComboBox.setPreferredSize(new java.awt.Dimension(100, 25));
		institutionsComboBox
				.addActionListener(new java.awt.event.ActionListener() {
					public void actionPerformed(java.awt.event.ActionEvent evt) {
						institutionsComboBoxActionPerformed(evt);
					}
				});
		jToolBar1.add(institutionsComboBox);
		jToolBar1.add(jSeparator1);

		addButton.setText("add");
		addButton.setFocusable(false);
		addButton.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
		addButton.setPreferredSize(new java.awt.Dimension(100, 25));
		addButton.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
		addButton.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent evt) {
				addButtonActionPerformed(evt);
			}
		});
		jToolBar1.add(addButton);

		updateButton.setText("update");
		updateButton.setFocusable(false);
		updateButton
				.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
		updateButton.setPreferredSize(new java.awt.Dimension(100, 25));
		updateButton.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
		updateButton.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent evt) {
				updateButtonActionPerformed(evt);
			}
		});
		jToolBar1.add(updateButton);

		deleteButton.setText("delete");
		deleteButton.setFocusable(false);
		deleteButton
				.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
		deleteButton.setPreferredSize(new java.awt.Dimension(100, 25));
		deleteButton.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
		deleteButton.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent evt) {
				deleteButtonActionPerformed(evt);
			}
		});
		jToolBar1.add(deleteButton);

		searchButton.setText("search");
		searchButton.setFocusable(false);
		searchButton
				.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
		searchButton.setPreferredSize(new java.awt.Dimension(100, 25));
		searchButton.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
		searchButton.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent evt) {
				searchButtonActionPerformed(evt);
			}
		});
		jToolBar1.add(searchButton);

		getContentPane().add(jToolBar1, java.awt.BorderLayout.PAGE_START);

		jToolBar2.setOrientation(javax.swing.SwingConstants.VERTICAL);
		jToolBar2.setRollover(true);

		serverpropertiesButton.setText("Server Properties");
		serverpropertiesButton.setFocusable(false);
		serverpropertiesButton
				.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
		serverpropertiesButton
				.setPreferredSize(new java.awt.Dimension(100, 25));
		serverpropertiesButton
				.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
		serverpropertiesButton
				.addActionListener(new java.awt.event.ActionListener() {
					public void actionPerformed(java.awt.event.ActionEvent evt) {
						serverpropertiesButtonActionPerformed(evt);
					}
				});
		jToolBar2.add(serverpropertiesButton);

		refreshButton.setText("Refresh");
		refreshButton.setFocusable(false);
		refreshButton
				.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
		refreshButton.setPreferredSize(new java.awt.Dimension(100, 25));
		refreshButton
				.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
		refreshButton.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent evt) {
				refreshButtonActionPerformed(evt);
			}
		});
		jToolBar2.add(refreshButton);

		getContentPane().add(jToolBar2, java.awt.BorderLayout.WEST);

		table.setModel(new javax.swing.table.DefaultTableModel(new Object[][] {
				{ null, null, null, null }, { null, null, null, null },
				{ null, null, null, null }, { null, null, null, null },
				{ null, null, null, null }, { null, null, null, null },
				{ null, null, null, null }, { null, null, null, null },
				{ null, null, null, null }, { null, null, null, null },
				{ null, null, null, null }, { null, null, null, null },
				{ null, null, null, null }, { null, null, null, null },
				{ null, null, null, null }, { null, null, null, null },
				{ null, null, null, null }, { null, null, null, null },
				{ null, null, null, null }, { null, null, null, null },
				{ null, null, null, null }, { null, null, null, null },
				{ null, null, null, null }, { null, null, null, null },
				{ null, null, null, null }, { null, null, null, null },
				{ null, null, null, null }, { null, null, null, null },
				{ null, null, null, null }, { null, null, null, null },
				{ null, null, null, null }, { null, null, null, null },
				{ null, null, null, null }, { null, null, null, null },
				{ null, null, null, null }, { null, null, null, null },
				{ null, null, null, null }, { null, null, null, null },
				{ null, null, null, null }, { null, null, null, null },
				{ null, null, null, null }, { null, null, null, null },
				{ null, null, null, null }, { null, null, null, null },
				{ null, null, null, null }, { null, null, null, null },
				{ null, null, null, null }, { null, null, null, null },
				{ null, null, null, null }, { null, null, null, null },
				{ null, null, null, null }, { null, null, null, null },
				{ null, null, null, null }, { null, null, null, null },
				{ null, null, null, null }, { null, null, null, null },
				{ null, null, null, null }, { null, null, null, null },
				{ null, null, null, null }, { null, null, null, null },
				{ null, null, null, null }, { null, null, null, null },
				{ null, null, null, null }, { null, null, null, null },
				{ null, null, null, null }, { null, null, null, null },
				{ null, null, null, null }, { null, null, null, null },
				{ null, null, null, null }, { null, null, null, null },
				{ null, null, null, null }, { null, null, null, null },
				{ null, null, null, null }, { null, null, null, null },
				{ null, null, null, null }, { null, null, null, null },
				{ null, null, null, null }, { null, null, null, null },
				{ null, null, null, null }, { null, null, null, null },
				{ null, null, null, null }, { null, null, null, null },
				{ null, null, null, null }, { null, null, null, null },
				{ null, null, null, null }, { null, null, null, null },
				{ null, null, null, null }, { null, null, null, null },
				{ null, null, null, null }, { null, null, null, null },
				{ null, null, null, null }, { null, null, null, null },
				{ null, null, null, null }, { null, null, null, null },
				{ null, null, null, null }, { null, null, null, null },
				{ null, null, null, null }, { null, null, null, null },
				{ null, null, null, null } }, new String[] { "First Name",
				"Last Name", "National ID Number", "Phone Number" }) {
			/**
			 * 
			 */
			private static final long serialVersionUID = 1L;
			Class[] types = new Class[] { java.lang.String.class,
					java.lang.String.class, java.lang.String.class,
					java.lang.String.class };
			boolean[] canEdit = new boolean[] { false, false, false, false };

			public Class getColumnClass(int columnIndex) {
				return types[columnIndex];
			}

			public boolean isCellEditable(int rowIndex, int columnIndex) {
				return canEdit[columnIndex];
			}
		});
		jScrollPane1.setViewportView(table);

		getContentPane().add(jScrollPane1, java.awt.BorderLayout.CENTER);
	}// </editor-fold>//GEN-END:initComponents

	private void addButtonActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_addButtonActionPerformed

		addorup(true);

		// TODO add your handling code here:
	}// GEN-LAST:event_addButtonActionPerformed

	private void updateButtonActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_updateButtonActionPerformed
		// TODO add your handling code here:
		addorup(false);
	}// GEN-LAST:event_updateButtonActionPerformed

	private void deleteButtonActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_deleteButtonActionPerformed
		// TODO add your handling code here:
		delorser(true);
	}// GEN-LAST:event_deleteButtonActionPerformed

	private void searchButtonActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_searchButtonActionPerformed
		// TODO add your handling code here:
		delorser(false);
	}// GEN-LAST:event_searchButtonActionPerformed

	private void serverpropertiesButtonActionPerformed(
			java.awt.event.ActionEvent evt) {// GEN-FIRST:event_serverpropertiesButtonActionPerformed
		JTextField cmp = new JTextField("localhost");
		String p = JOptionPane.showInputDialog(cmp, "1099");
		if (p != null) {
			serverLocation = cmp.getText();
			port = Integer.valueOf(p);
			try {
				this.client = new Client(serverLocation, port, callHandler);
			} catch (IOException ex) {
				Logger.getLogger(LightApp.class.getName()).log(Level.SEVERE,
						null, ex);
			}
		} else {

		}
	}// GEN-LAST:event_serverpropertiesButtonActionPerformed

	private void refreshButtonActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_refreshButtonActionPerformed
		filtab(); // TODO add your handling code here:
	}// GEN-LAST:event_refreshButtonActionPerformed

	private void institutionsComboBoxActionPerformed(
			java.awt.event.ActionEvent evt) {// GEN-FIRST:event_institutionsComboBoxActionPerformed
		filtab(); // TODO add your handling code here:
	}// GEN-LAST:event_institutionsComboBoxActionPerformed

	// Variables declaration - do not modify//GEN-BEGIN:variables
	private javax.swing.JButton addButton;
	private javax.swing.JButton deleteButton;
	@SuppressWarnings("rawtypes")
	private javax.swing.JComboBox institutionsComboBox;
	private javax.swing.JScrollPane jScrollPane1;
	private javax.swing.JToolBar.Separator jSeparator1;
	private javax.swing.JToolBar jToolBar1;
	private javax.swing.JToolBar jToolBar2;
	private javax.swing.JButton refreshButton;
	private javax.swing.JButton searchButton;
	private javax.swing.JButton serverpropertiesButton;
	private javax.swing.JTable table;
	private javax.swing.JButton updateButton;

	// End of variables declaration//GEN-END:variables

	private void addorup(boolean au) {
		JTextField[] cmp = new JTextField[3];
		cmp[0] = new JTextField("First Name");
		cmp[1] = new JTextField("Last Name");
		cmp[2] = new JTextField("National ID Number");
		String p = JOptionPane.showInputDialog(cmp, "Phone Number");

		if (p != null) {
			Employee emp = new Employee(cmp[0].getText(), cmp[1].getText(),
					cmp[2].getText(), p, institutionsComboBox.getSelectedItem()
							.toString());
			if (au) {
				int ret = service.addEmployee(emp);

				if (ret == -1) {
					JOptionPane.showMessageDialog(this, "Server failure.",
							"Data entry", JOptionPane.INFORMATION_MESSAGE);
				} else if (ret == 0) {
					JOptionPane.showMessageDialog(this, "Unknown failure.",
							"Data entry", JOptionPane.INFORMATION_MESSAGE);
				} else {
					JOptionPane.showMessageDialog(
							this,
							"First name: "
									+ cmp[0].getText()
									+ "\nLast name: "
									+ cmp[0].getText()
									+ "\nNationel Id Number: "
									+ cmp[0].getText()
									+ "\nPhone number: "
									+ p
									+ " successfully added to "
									+ institutionsComboBox.getSelectedItem()
											.toString(), "Data entry",
							JOptionPane.INFORMATION_MESSAGE);
				}

			} else {
				int ret = service.updateEmployee(emp);

				if (ret == -1) {
					JOptionPane.showMessageDialog(this, "Server failure.",
							"Data entry", JOptionPane.INFORMATION_MESSAGE);
				} else if (ret == 0) {
					JOptionPane.showMessageDialog(this, "Unknown failure.",
							"Data entry", JOptionPane.INFORMATION_MESSAGE);
				} else {
					JOptionPane.showMessageDialog(
							this,
							"First name: "
									+ cmp[0].getText()
									+ "\nLast name: "
									+ cmp[0].getText()
									+ "\nNationel Id Number: "
									+ cmp[0].getText()
									+ "\nPhone number: "
									+ p
									+ " successfully added to "
									+ institutionsComboBox.getSelectedItem()
											.toString(), "Data entry",
							JOptionPane.INFORMATION_MESSAGE);
				}

			}

		} else {
		}
	}

	private void delorser(boolean au) {
		String m = JOptionPane.showInputDialog("First Name");
		if (m != null) {
			if (au) {
				int ret = service.deleteEmployee(m, institutionsComboBox
						.getSelectedItem().toString());

				if (ret == -1) {
					JOptionPane.showMessageDialog(this, "Server failure.",
							"Data entry", JOptionPane.INFORMATION_MESSAGE);
				} else if (ret == 0) {
					JOptionPane.showMessageDialog(this, "Unknown failure.",
							"Data entry", JOptionPane.INFORMATION_MESSAGE);
				} else {
					JOptionPane.showMessageDialog(this, m + " from "
							+ institutionsComboBox.getSelectedItem().toString()
							+ " successfully delleted.", "Data entry",
							JOptionPane.INFORMATION_MESSAGE);
				}

			} else {
				Employee emp = service.searchEmployee(m, institutionsComboBox
						.getSelectedItem().toString());

				if (emp == null) {
					JOptionPane.showMessageDialog(this, "Employee not found.",
							"Data entry", JOptionPane.INFORMATION_MESSAGE);
				} else {
					JOptionPane.showMessageDialog(this,
							"First name: " + emp.getFirstName() + "\n"
									+ "Last name: " + emp.getLastName() + "\n"
									+ "Nationel Id Number: " + emp.getCin()
									+ "\n" + "Phone number: " + emp.getTel(),
							"Data entry", JOptionPane.INFORMATION_MESSAGE);
				}
			}
		} else {

		}
	}

	void filtab() {
		table.setModel(new javax.swing.table.DefaultTableModel(new Object[][] // TODO
				{// Service.getServiceInstance().getInstitution(institutionsComboBox.getSelectedItem().toString()).getEmployeesList()
				{ null, null, null, null }, { null, null, null, null },
						{ null, null, null, null }, { null, null, null, null },
						{ null, null, null, null }, { null, null, null, null },
						{ null, null, null, null }, { null, null, null, null },
						{ null, null, null, null }, { null, null, null, null },
						{ null, null, null, null }, { null, null, null, null },
						{ null, null, null, null }, { null, null, null, null },
						{ null, null, null, null }, { null, null, null, null },
						{ null, null, null, null }, { null, null, null, null },
						{ null, null, null, null }, { null, null, null, null },
						{ null, null, null, null }, { null, null, null, null },
						{ null, null, null, null }, { null, null, null, null },
						{ null, null, null, null }, { null, null, null, null },
						{ null, null, null, null }, { null, null, null, null },
						{ null, null, null, null }, { null, null, null, null },
						{ null, null, null, null }, { null, null, null, null },
						{ null, null, null, null }, { null, null, null, null },
						{ null, null, null, null }, { null, null, null, null },
						{ null, null, null, null }, { null, null, null, null },
						{ null, null, null, null }, { null, null, null, null },
						{ null, null, null, null }, { null, null, null, null },
						{ null, null, null, null }, { null, null, null, null },
						{ null, null, null, null }, { null, null, null, null },
						{ null, null, null, null }, { null, null, null, null },
						{ null, null, null, null }, { null, null, null, null },
						{ null, null, null, null }, { null, null, null, null },
						{ null, null, null, null }, { null, null, null, null },
						{ null, null, null, null }, { null, null, null, null },
						{ null, null, null, null }, { null, null, null, null },
						{ null, null, null, null }, { null, null, null, null },
						{ null, null, null, null }, { null, null, null, null },
						{ null, null, null, null }, { null, null, null, null },
						{ null, null, null, null }, { null, null, null, null },
						{ null, null, null, null }, { null, null, null, null },
						{ null, null, null, null }, { null, null, null, null },
						{ null, null, null, null }, { null, null, null, null },
						{ null, null, null, null }, { null, null, null, null },
						{ null, null, null, null }, { null, null, null, null },
						{ null, null, null, null }, { null, null, null, null },
						{ null, null, null, null }, { null, null, null, null },
						{ null, null, null, null }, { null, null, null, null },
						{ null, null, null, null }, { null, null, null, null },
						{ null, null, null, null }, { null, null, null, null },
						{ null, null, null, null }, { null, null, null, null },
						{ null, null, null, null }, { null, null, null, null },
						{ null, null, null, null }, { null, null, null, null },
						{ null, null, null, null }, { null, null, null, null },
						{ null, null, null, null }, { null, null, null, null },
						{ null, null, null, null }, { null, null, null, null },
						{ null, null, null, null }

				}, new String[] { "First name", "Last name",
						"National Id Number", "Phone number" }) {
			/**
                     *
                     */
			private static final long serialVersionUID = 1L;
			@SuppressWarnings("rawtypes")
			Class[] types = new Class[] { java.lang.String.class,
					java.lang.String.class, java.lang.String.class,
					java.lang.String.class };
			boolean[] canEdit = new boolean[] { false, false, false, false };

			@Override
			public Class<?> getColumnClass(int columnIndex) {
				return types[columnIndex];
			}

			@Override
			public boolean isCellEditable(int rowIndex, int columnIndex) {
				return canEdit[columnIndex];
			}
		});

		Institution inst = null;

		try {
			inst = service.getInstitution(institutionsComboBox
					.getSelectedItem().toString());
			List<String[]> list = inst.getEmployeesList();
			TableModel m = table.getModel();

			int i = 0, j = 0;
			for (String[] strings : list) {
				for (j = 0; j < 4; j++) {
					m.setValueAt(strings[j], i, j);
				}
				i++;
			}

		} catch (Exception e) {
			JOptionPane
					.showMessageDialog(
							this,
							"Please check service configuration or the service backbone.",
							"Unable to invoke service",
							JOptionPane.WARNING_MESSAGE);
		}

	}
}
